import 'dart:io';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Chat',
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  List<String> messages = [];
  final TextEditingController _controller = TextEditingController();
  Socket? _socket;

  @override
  void initState() {
    super.initState();
    _initSocket();
  }

  void _initSocket() async {
    try {
      _socket = await Socket.connect('192.168.1.7', 8007);
      print('Connected to the server');
      _socket!.listen((List<int> event) {
        final message = String.fromCharCodes(event);
        print('Received from server: $message');
        setState(() {
          messages.add(message);
        });
      });
    } catch (e) {
      print('Failed to connect: $e');
    }
  }

  void _sendMessage() {
    final text = _controller.text;
    if (text.isNotEmpty) {
      print('Sending to server: $text');
      _socket?.write(text + '\n');
      _controller.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Chat'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: messages.length,
              itemBuilder: (_, index) => ListTile(
                title: Text(messages[index]),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _controller,
              decoration: InputDecoration(hintText: 'Send a message'),
              onSubmitted: (_) => _sendMessage(),
            ),
          ),
        ],
      ),
    );
  }
}
